#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "wifi_device.h"
#include "wifi_hotspot_config.h"
#include "iot_gpio.h"
// #include "kh_device_info.h"

#define KEY_GPIO_PIN (34) // 替换为实际的KEY GPIO引脚
#define TIMEOUT_MS 30000  // 超时时间，单位毫秒

static WifiErrorCode wifi_error;
static WifiEvent g_wifiEventHandler = {0};

// 事件处理函数
static void OnHotspotStaJoinHandler(StationInfo *info)
{
    (void)info;
    printf("STA joined AP\n");
}

static void OnHotspotStaLeaveHandler(StationInfo *info)
{
    (void)info;
    printf("STA left AP\n");
}

static void OnHotspotStateChangedHandler(int state)
{
    printf("Hotspot state changed: state = %d\n", state);
}

// Wi-Fi初始化
static void WiFiInit(void)
{
    printf("<-- Wi-Fi Init -->\n");
    g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;
    g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;
    g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;
    wifi_error = RegisterWifiEvent(&g_wifiEventHandler);
    if (wifi_error != WIFI_SUCCESS)
    {
        printf("Register Wi-Fi event failed! Error code: %d\n", wifi_error);
    }
    else
    {
        printf("Register Wi-Fi event succeeded!\n");
    }
}

// 初始化Wi-Fi AP模式
static void InitWifiAp(void)
{
    printf("Initializing Wi-Fi AP mode...\n");
    WiFiInit();

    const char *sn = getDeviceSN();
    // if (strlen(sn) != 18)
    // {
    //     printf("sn is invalid.\r\n");
    //     return;
    // }
    if (sn)
    {
        printf("++++++++++++++++getSnDemo SN is [%s]++[]\n", sn);
    }
    char ssid[16]; // 确保数组足够大以存储新的SSID

    // 使用强制类型转换int数据的方法判断是否为0
    if (sn && (intptr_t)sn != 0)
    {
        size_t len = strlen(sn);
        snprintf(ssid, sizeof(ssid), "IC204%s", sn + len - 4);
    }
    else
    {
        snprintf(ssid, sizeof(ssid), "IC2040000");
    }
    printf("++++++++++++++++wifiAPName is [%s]\n", ssid);
    HotspotConfig ap_config = {
        .ssid = ssid,
        .preSharedKey = "123456789",
        .securityType = WIFI_SEC_TYPE_PSK,
    };
    if (SetHotspotConfig(&ap_config) != WIFI_SUCCESS)
    {
        printf("Set hotspot config failed, error code: %d\n", wifi_error);
        return;
    }
    if (EnableHotspot() != WIFI_SUCCESS)
    {
        printf("Enable hotspot failed, error code: %d\n", wifi_error);
        return;
    }
    printf("Wi-Fi AP mode enabled\n");
}

// 禁用Wi-Fi AP模式
static void DisableWifiAp(void)
{
    printf("Disabling Wi-Fi AP mode...\n");
    if (DisableHotspot() != WIFI_SUCCESS)
    {
        printf("Disable hotspot failed, error code: %d\n", wifi_error);
        return;
    }
    printf("Wi-Fi AP mode disabled\n");
}

// 检查KEY是否按下，并根据状态开启或关闭Wi-Fi AP模式
static void CheckKeyAndToggleWifiAp(IotGpioValue *inputValuePtr, bool wifiApEnabled, uint64_t *lastKeyPressedTime)
{
    printf("CheckKeyAndToggleWifiAp E\n");
    IotGpioValue inputValue;
    IotGpioValue outputValue;
    IoTGpioInit(KEY_GPIO_PIN);
    IoTGpioInit(22);
    IoTGpioSetDir(KEY_GPIO_PIN, IOT_GPIO_DIR_IN);
    IoTGpioSetDir(22, IOT_GPIO_DIR_OUT);
    IoTGpioGetInputVal(KEY_GPIO_PIN, &inputValue);
    IoTGpioGetInputVal(22, &outputValue);
    printf("000000000 IoTGpioGetInputVal inputValue:...%d  outputValue:...%d\n", inputValue, outputValue);
    osDelay(100);

    if (inputValue == 0)
    { // 假设按键按下为低电平，初始化为高电平
        printf("1111111111 IoTGpioGetInputVal inputValue:...%d  outputValue:...%d\n", inputValue, outputValue);
        if (!wifiApEnabled)
        {
            printf("KEY pressed, enabling Wi-Fi AP mode...\n");
            printf("00000000 wifiApEnabled:...%d\n", wifiApEnabled);
            *lastKeyPressedTime = osKernelGetSysTimerCount();                           // 记录按键按下的时间
            printf("00000000 lastKeyPressedTime = %" PRIu64 "\n", *lastKeyPressedTime); // 打印当前时间和最后按键时间
            InitWifiAp();
            wifiApEnabled = true;
        }
    }
    else
    {
        if (wifiApEnabled)
        {
            uint64_t currentTime = osKernelGetSysTimerCount();
            if ((currentTime - *lastKeyPressedTime) > TIMEOUT_MS)
            {
                printf("1111111 currentTime = %" PRIu64 ", lastKeyPressedTime = %" PRIu64 "\n", currentTime, *lastKeyPressedTime); // 打印当前时间和最后按键时间
                printf("KEY not pressed for 30 seconds, disabling Wi-Fi AP mode...\n");
                printf("1111111 wifiApEnabled:...%d\n", wifiApEnabled);
                DisableWifiAp();
                wifiApEnabled = false;
            }
        }
    }
    printf("CheckKeyAndToggleWifiAp E\n");
}

void WifiApTask(void)
{
    printf("WifiApTask E\n");
    IotGpioValue inputValue;
    bool wifiApEnabled = false;
    uint64_t lastKeyPressedTime = 0;

    printf("Wi-Fi AP mode demo start!\n");
    while (1)
    {
        CheckKeyAndToggleWifiAp(&inputValue, wifiApEnabled, &lastKeyPressedTime);
        osDelay(100); // 稍微延时，减少CPU占用
    }
    printf("WifiApTask X\n");
}

void WifiApDemo(void)
{
    printf("WifiApDemo E\n");
    osThreadAttr_t attr;
    attr.name = "WIFI_AP_TASK";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 0x1000;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)WifiApTask, NULL, &attr) == NULL)
    {
        printf("Failed to create thread!\n");
    }
    printf("WifiApDemo X\n");
}

APP_FEATURE_INIT(WifiApDemo);